<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<script type="text/javascript" src="${basePath}/static/js/util.js"></script>
<script type="text/javascript" src="${basePath}/static/publics/assets/layer/layer.js"></script>

<script src="${basePath}/static/js/rotate/jquery.rotate.min.js"></script>
<link href="${basePath}/static/css/Catalog/CatalogManage.css" rel="stylesheet" type="text/css">
<link href="${basePath}/static/layer/layer_defined.css" rel="stylesheet" type="text/css">

<style>
.TM
{
	display: block;
	filter: alpha(opacity=10); /*IE*/
	-moz-opacity: 0.5; /*Mozilla*/
	opacity: 0.5; /*FF*/
}
#batchChooseTemplate a:hover {
	color:#6c6f6f; 
	background:#FEC99C;
}
</style>


<div class="file_manage">

    <div class="file_title">
    	<c:if test="${not empty hospitalizationNotes }">
    		<h3>${hospitalizationNotes[0].name}&nbsp;&nbsp;${hospitalizationNotes[0].id_number}&nbsp;&nbsp;<fmt:formatDate value="${hospitalizationNotes[0].out_hospital_date}" pattern="yyyy-MM-dd"/> ${hospitalizationNotes[0].treatment_type_name}&nbsp;&nbsp;</h3>
    	</c:if>
    	
    	<form action="${basePath}/medrecord/paginationMedrecordImages" hidden="true" id="paginationForm">
    		<input type="hidden" id="firstGuid" name="firstGuid" value="${param.firstGuid }">
    		<input type="hidden" id="paginationStatus" name="paginationStatus" value=""/>
    		<input class="input_box" type="hidden"  name="name" id='name' value='${params.name }' />
			<input class="input_box" type="hidden"  name="idCard" id='idCard' value='${params.idCard}' />
			<input name="outHospitalStartDate" id="outHospitalStartDate" value="<fmt:formatDate value="${params.outHospitalStartDate}" pattern="yyyy-MM-dd"/>"  type="hidden"> 
			<input  name="outHospitalEndDate" id="outHospitalEndDate" value="<fmt:formatDate value="${params.outHospitalEndDate}" pattern="yyyy-MM-dd"/>"  type="hidden">
			<input class="input_box" type="hidden" id="mrId"  name="mrId" value='${params.mrId}' />
			<input class="input_box" type="hidden"  name="visitNumber" id='visitNumber' value='${params.visitNumber}' />
    		<input type="hidden" id="currentPage" name="currentPage" value="${params.currentPage}">
    	</form>
        <input type="hidden" id="firstGuidHidden" value="${param.firstGuid }">
        <ul style="width:182px;">
       		 <li ><a href="javascript:deleteCertainPageTypeImgs()" >删除</a></li>
            <li ><a onclick="addPageStatus()" id="closeBtn2">编页完成</a> <!-- <a onclick="custom_close()" id="closeBtn2">关闭</a> --></li>
        </ul>
    </div>
    <div class="fileContent clearfix">
        <div class="fileContent-left">
            <div class="file_header">
                <div class="left">文件信息&nbsp;&nbsp;
                <select onchange="paginationShow()" id="pagination" style="width:80px;" class="input_box">
                	
                	<c:if test="${paginationStatus==1}">
                		<option selected="selected" value="1">未编页</option>
                		<option value="2">已编页</option>
                	</c:if>
                	<c:if test="${paginationStatus==2}">
                		<option  value="1">未编页</option>
                		<option selected="selected" value="2">已编页</option>
                	</c:if>
                	
                
                </select></div>
                <div class="right">总页数:&nbsp;<span id="totalFileCount">0</span>&nbsp;&nbsp; 未编页 &nbsp;<span id="unPaginationSpan">0</span></div>
            </div>
        <!--<h4 style="height:35px;line-height: 35px;width:965px;margin:0 0 5px;background:#e3e5e4;padding-left:25px;">文件对照信息</h4>-->
            <div class="filePage" id="filepage" style="height:1200px;">
                <ul style="position:relative;">
                	<c:forEach var="scanFile" items="${scanFiles }" varStatus="status" >
                		<c:choose>
               				<c:when test="${not empty scanFile.mr_page_type_id}">
               					<!-- 已经编页  data_index 编页标签的sort_code, sortIndex 是图片的原始名 -->
               					<li tabindex="100" style="position:relative" id="${ scanFile.fileHash}" style="border-color: green; position:relative" sort_index= ${scanFile.sortIndex} 
               								data-index="${scanFile.dataIndex }" data-filename="${scanFile.mr_page_type_id}" file-hash="${ scanFile.fileHash}" mr-page_type_id ="${ scanFile.mr_page_type_id}">
                					<c:choose>
               							<c:when test="${scanFile.status==1}">
                							<input checked="checked" class="check_cl" file-hash="${ scanFile.fileHash}"  onclick="changePrintStatus(this)" 
                									style="position:absolute;top:0;right:0" type="checkbox" class="check_cl" name="">
		                				</c:when>
               							<c:otherwise>
               								<input class="check_cl"  file-hash="${ scanFile.fileHash}" onclick="changePrintStatus(this)"   
               										style="position:absolute;top:0;right:0" type="checkbox" class="check_cl" name="">
               							</c:otherwise>
               						</c:choose>
               						
		                			<img src="${scanFile.hospitalizationNoteResourceUrl}${scanFile.fileUrl}${scanFile.fileName}?date=${newDate}" alt=""/>
		                			
		                			<div style="position:absolute;top:0;right:4%;">
		                				<a class="int" onclick="deleteImg(this)">删除</a>
		                			</div>
		                			<div style="position:absolute;top:0;right:9%">
		                				<a class="int" imgpath="${scanFile.fileUrl}${scanFile.fileName}"  onclick="rotateImg(this)">翻转</a>
		                			</div>
		                			<div style="position:absolute;top:0;right:14%;">
		                				<input style="width:50px;height:20px" class="changeImgIndex" type="input" value="${scanFile.sortIndex}"/>
		                				<a class="int"   onclick="sortImage(this);stopBubble(this);" >序列</a>
		                			</div>
		                		</li>
		                	</c:when>
		                	
               				<c:otherwise>
               					<!-- 未编页  -->
               					<li tabindex="100" style="position:relative" id="${ scanFile.fileHash}" data-filename="0" data-index="10000" sort_index= ${scanFile.sortIndex} file-hash="${ scanFile.fileHash}">
		                			<img  src="${scanFile.hospitalizationNoteResourceUrl}${scanFile.fileUrl}${scanFile.fileName}?date=${newDate}" alt=""/>
		                			<div style="position:absolute;top:0;right:0;">
		                				<a class="int" onclick="deleteImg(this)">删除</a>
		                			</div>
		                			<div style="position:absolute;top:0;right:5%">
		                				<a class="int" imgpath="${scanFile.fileUrl}${scanFile.fileName}"  onclick="rotateImg(this)">翻转</a>
		                			</div>
		                			<div style="position:absolute;top:0;right:10%;">
		                				<input style="width:50px;height:20px" class="changeImgIndex" type="input" value="${scanFile.sortIndex}"/>
		                				<a class="int"   onclick="sortImage(this);stopBubble(this);">序列</a>
		                			</div>
		                		</li>
               				</c:otherwise>
               				
               			</c:choose>
                	</c:forEach>  
                </ul>
            </div>
        </div>
      
      <div class="file_menu">
        <div style="width:344px;height:40px;line-height:40px;color:#FFF;background-color:#009388;text-align:center;">病案编目管理</div>
        	<!-- 左边的编页标签 -->
	        <ul class="clearfix menulist" >
	        	<c:forEach var="mrPageType" items="${mrPageTypes}"  varStatus="status">
	            	<c:if test="${(mrPageSizes/2) > status.index}">
	            	<li class="file_li" style="overflow-y: hidden;" id="m3_${mrPageType.id}" sortCode="${mrPageType.sortCode}"  page-type-id="${mrPageType.id }" data-filename="${mrPageType.id }" title="${mrPageType.name}">
		            	<a><span>${mrPageType.name }</span>
								<c:choose>
									<c:when test="${not empty mrPageTypesOfPaginationMap[mrPageType.id]}">
										<span id="mrpagetype${mrPageType.id}">${mrPageTypesOfPaginationMap[mrPageType.id].pagination_count}</span>
									</c:when>
									<c:otherwise><span id="mrpagetype${mrPageType.id}">0</span></c:otherwise>
								</c:choose>
						</a>
					</li>
					</c:if>
	            </c:forEach>
	        </ul>
        	
        	<!-- 右边的编页标签  -->
	         <ul class="clearfix ul1 menulist" style="height: 1200px; ">
	        	<c:forEach var="mrPageType" items="${mrPageTypes}" varStatus="status">
		            <c:if test="${(mrPageSizes/2) <= status.index}">
		            	<li class="file_li" style="overflow-y: hidden;"  id="m3_${mrPageType.id}" sortCode="${mrPageType.sortCode}" page-type-id="${mrPageType.id }" data-filename="${mrPageType.id }" title="${mrPageType.name}">
			            	<a><span>${mrPageType.name }</span>
									<c:choose>
										<c:when test="${not empty mrPageTypesOfPaginationMap[mrPageType.id]}">
											<span id="mrpagetype${mrPageType.id}">${mrPageTypesOfPaginationMap[mrPageType.id].pagination_count}</span>
										</c:when>
										<c:otherwise><span id="mrpagetype${mrPageType.id}">0</span></c:otherwise>
									</c:choose>
							</a>
						</li>
					</c:if>
	            </c:forEach>
	        </ul>
    </div>
    </div>
</div>

<div class="modal fade" id="batchChooseTemplate" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog" style="width: 1280px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">编页标签</h4>
            </div>
            <div class="modal-body" style="overflow: hidden;">
            	<input type="hidden" id="batchChooseTemplate_startIndex">
            	<input type="hidden" id="batchChooseTemplate_endIndex">
              	<ul style="width:1290px;">
		        	<c:forEach var="mrPageType" items="${mrPageTypes}"  varStatus="status">
		            	<li style="width:200px; height:30px; text-align:center;float: left;margin-right:10px;line-height:30px; color:#555555; font-size:14px; margin-bottom:10px;background: #F7F8F8">
			            	<a style="width: 100%;display: block;" href="javascript:submitBatchPaginantion(${mrPageType.id})">${mrPageType.name }</a>
						</li>
		            </c:forEach>
	       		</ul>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!-- 删除某个标签模态框 -->
<div class="modal fade" id="deleteCertainPageTypeImgsModal" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog" >
        <div class="modal-content" style="height: 200px;">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" >删除某个标签对应的所有图片</h4>
            </div>
            <div class="modal-body" style="text-align: center;">
	            <form class="form-inline" id="deleteCertainPageTypeImgsModal_form">
					  <div class="form-group">
						    <label style="font-size: 16px;">编页标签</label>
						    <select class="form-control" id="select_deleteCertainPageTypeImg">
						 		<option value="">删除所有</option>
		            			<c:forEach var="mrPageType" items="${mrPageTypes}"  varStatus="status">
		            				<option value="${mrPageType.id}">${mrPageType.name }</option>
		            			</c:forEach>
		            		</select>
					  </div>
				</form>
			</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="deleteCertainPageTypeImgs_button()">删除</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<input type="hidden" id="hospitalizationNoteResourceUrl" value="${hospitalizationNoteResourceUrl}">
<script>
var keyCodeTable = [
	{keyName:'a',keyCode:97},
	{keyName:'b',keyCode:98},
	{keyName:'c',keyCode:99},
	{keyName:'d',keyCode:100},
	{keyName:'e',keyCode:101},
	{keyName:'f',keyCode:102},
	{keyName:'g',keyCode:103},
	{keyName:'h',keyCode:104},
	{keyName:'i',keyCode:105},
	{keyName:'j',keyCode:106},
	{keyName:'k',keyCode:107},
	{keyName:'l',keyCode:108},
	{keyName:'m',keyCode:109},
	{keyName:'n',keyCode:110},
	{keyName:'o',keyCode:111},
	{keyName:'p',keyCode:112},
	{keyName:'q',keyCode:113},
	{keyName:'r',keyCode:114},
	{keyName:'s',keyCode:115},
	{keyName:'t',keyCode:116},
	{keyName:'u',keyCode:117},
	{keyName:'v',keyCode:118},
	{keyName:'w',keyCode:119},
	{keyName:'x',keyCode:120},
	{keyName:'y',keyCode:121},
	{keyName:'z',keyCode:122},
	
	{keyName:'0',keyCode:48},
	{keyName:'1',keyCode:49},
	{keyName:'2',keyCode:50},
	{keyName:'3',keyCode:51},
	{keyName:'4',keyCode:52},
	{keyName:'5',keyCode:53},
	{keyName:'6',keyCode:54},
	{keyName:'7',keyCode:55},
	{keyName:'8',keyCode:56},
	{keyName:'9',keyCode:57}
]; 

function getKeyNameByMrPageTypeId(mrPageTypeId) {
	if (null != mrPageTypeRelevanceKeyCode && mrPageTypeRelevanceKeyCode.length > 0) {
		for (var i = 0; i < mrPageTypeRelevanceKeyCode.length; i++) {
			if (mrPageTypeRelevanceKeyCode[i].pageTypeId == mrPageTypeId) {
				return "("+mrPageTypeRelevanceKeyCode[i].keyName+")"
			}
		}
	}
	
	return "";
}

function getKeyNameByKeyCode(keyCode) {
	var keyName = null;
	if (null != keyCodeTable && keyCodeTable.length > 0) {
		for (var i = 0; i < keyCodeTable.length; i++) {
			if (keyCodeTable[i].keyCode == keyCode) {
				keyName = keyCodeTable[i].keyName;
				break;
			}
		}
	}
	return keyName;
}

function getMrPageTypeIdByKeyName(keyName) {
	var pageTypeId = null;

	if (null != mrPageTypeRelevanceKeyCode && mrPageTypeRelevanceKeyCode.length > 0) {
		for (var i = 0; i < mrPageTypeRelevanceKeyCode.length; i++) {
			if (mrPageTypeRelevanceKeyCode[i].keyName == keyName) {
				pageTypeId = mrPageTypeRelevanceKeyCode[i].pageTypeId;
				break;
			}
		}
	}
	
	return pageTypeId;
}

function getMrPageTypeSortCodeByKeyName(keyName) {
	var sortCode = null;

	if (null != mrPageTypeRelevanceKeyCode && mrPageTypeRelevanceKeyCode.length > 0) {
		for (var i = 0; i < mrPageTypeRelevanceKeyCode.length; i++) {
			if (mrPageTypeRelevanceKeyCode[i].keyName == keyName) {
				sortCode = mrPageTypeRelevanceKeyCode[i].sortCode;
				break;
			}
		}
	}
	
	return sortCode;
}

var mrPageTypeRelevanceKeyCode = [
									{'pageTypeId':1, 'sortCode':1, 'name':'病案首页','keyName':'q'}, {'pageTypeId':3,'sortCode':4,'name':'入院记录(死亡)','keyName':'w'}, 
									{'pageTypeId':4, 'sortCode':5, 'name':'病程记录','keyName':'e'}, {'pageTypeId':18,'sortCode':31,'name':'出院小结','keyName':'r'},
									{'pageTypeId':24, 'sortCode':37, 'name':'知情同意书','keyName':'s'},{'pageTypeId':26, 'sortCode':39, 'name':'会诊单','keyName':'h'},
									
									{'pageTypeId':29, 'sortCode':42, 'name':'检验记录单','keyName':'d'},{'pageTypeId':37, 'sortCode':50, 'name':'心电图','keyName':'x'},
									{'pageTypeId':38, 'sortCode':51, 'name':'动态心电图','keyName':'c'},{'pageTypeId':39, 'sortCode':52, 'name':'动态血压','keyName':'v'},
									
									{'pageTypeId':43, 'sortCode':56, 'name':'超声报告','keyName':'j'},{'pageTypeId':44, 'sortCode':57, 'name':'放射科报告','keyName':'k'},
									{'pageTypeId':46, 'sortCode':59, 'name':'体温单','keyName':'t'},{'pageTypeId':47, 'sortCode':60, 'name':'医嘱记录单','keyName':'y'},
									
									{'pageTypeId':48, 'sortCode':61, 'name':'生命体征记录单','keyName':'i'},{'pageTypeId':49, 'sortCode':610, 'name':'特别护理记录','keyName':'n'},
									{'pageTypeId':57, 'sortCode':620, 'name':'病危(重)护理单','keyName':'m'},{'pageTypeId':50, 'sortCode':630, 'name':'护理综合评估单','keyName':'g'},
									{'pageTypeId':54, 'sortCode':660, 'name':'复印资料','keyName':'f'},{'pageTypeId':5, 'sortCode':6, 'name':'手术同意书','keyName':'1'},
									
									{'pageTypeId':7, 'sortCode':8, 'name':'麻醉同意书','keyName':'2'},{'pageTypeId':8, 'sortCode':9, 'name':'麻醉术前访视单','keyName':'3'},
									{'pageTypeId':9, 'sortCode':10, 'name':'手术安全核查','keyName':'4'},{'pageTypeId':10, 'sortCode':11, 'name':'手术风险评估','keyName':'5'},
									
									{'pageTypeId':12, 'sortCode':13, 'name':'手术清点记录','keyName':'6'},{'pageTypeId':13, 'sortCode':14, 'name':'麻醉记录','keyName':'7'},
									{'pageTypeId':15, 'sortCode':16, 'name':'手术记录','keyName':'8'},{'pageTypeId':16, 'sortCode':17, 'name':'麻醉术后访视记录','keyName':'9'},
									
									{'pageTypeId':17, 'sortCode':18, 'name':'术后病程记录','keyName':'0'},{'pageTypeId':28, 'sortCode':41, 'name':'病理报告','keyName':'l'},
									{'pageTypeId':41, 'sortCode':54, 'name':'血栓弹力图','keyName':'o'},{'pageTypeId':40, 'sortCode':53, 'name':'踏车实验+平板','keyName':'p'},
									
									{'pageTypeId':53, 'sortCode':2, 'name':'查体记录','keyName':'u'}
								];



function changePrintStatus(obj){
	var status= $(obj).prop('checked')==true?1:2;
	var firstguid = $("#firstGuidHidden").val();
 	var filehash =  $(obj).attr("file-hash");
 	
 	//alert(firstguid+"--"+filehash+"--"+status);
 	$.ajax({
 		type:"post",
 		data:{status:status,firstGuid:firstguid,fileHash:filehash},
 		url:"${basePath}/medrecord/updateMedResource",
 		success:function(data){
 		
 		}
 	})
}




$(function(){
	paginationCount();
})

function paginationCount(){
	var firstGuid=$("#firstGuid").val();
	$.ajax({
		type:"post",
		data:{firstGuid:firstGuid},
		url:"${basePath}/medrecord/scanFilePaginationCount",
		success:function(data){
			if(data){
				$("#totalFileCount").html(data.scanFileCount);
				$("#unPaginationSpan").html(data.unPaginationFileCount);
			}
		}
	})
}




function paginationShow(){
	var pagination = $("#pagination").val();
	if(pagination==1){
		$("#paginationStatus").val(1);
	}else{
		$("#paginationStatus").val(2);
	}
	
	
	$("#paginationForm").submit();
}



function checkNumber(theObj) {
	  var reg = /^[0-9]+.?[0-9]*$/;
	  if (reg.test(theObj)) {
	    return true;
	  }
	  return false;
	}


	function sort_li(a, b){
		var sortIndexB =$(b).attr('sort_index');
		var sortIndexA =$(a).attr('sort_index');
		var dataIndexB=$(b).attr('data-index');
		var dataIndexA=$(a).attr('data-index');
		
		if((dataIndexB ==  dataIndexA)){
			if(checkNumber(sortIndexB) && checkNumber(sortIndexA)){
				 return Number(sortIndexB) < Number(sortIndexA) ? 1 : -1;
			}
		}
	
		
        return Number($(b).attr('data-index')) < Number($(a).attr('data-index')) ? 1 : -1;    //升序排列
    }
   
	function existsSBatchChoose() {
		var flag = false;
		$("#filepage li").each(function(index) {
			if ($(this).attr("s_batchChoose")=='s_batchChoose') {
				flag = true;
			}
		});
		
		return flag;
	}
	
	function getBatchChooseIndex(str) {
		var batchChooseindex = -1;
		
		$("#filepage li").each(function(index) {
			if($(this).attr(str) ) {
				batchChooseindex = index;
			}		
		});
		return batchChooseindex;
	}
	
	function getMedicalResourceJsonStr(startIndex, endIndex, pageTypeId) {
		var medicalResourceList = [];
		
		$("#filepage li").each(function(index) {
			if (index >= startIndex && index <= endIndex) {
				var medicalResourceObject = new Object();
				medicalResourceObject.fileHash = $(this).attr("file-hash");
				medicalResourceObject.oldMrPageTypeId = $(this).attr("mr-page_type_id");
				medicalResourceList.push(medicalResourceObject);
			}	
		});
		
		 var medicalResourceJsonStr = JSON.stringify(medicalResourceList);
		 console.log(medicalResourceJsonStr);
	     return medicalResourceJsonStr;
	}
	
	
	function batchPaginaionAjax(startIndex, endIndex, mrpagetypeid) {
      	var firstguid = $("#firstGuidHidden").val();
      	var medicalResourceJsonStr  = getMedicalResourceJsonStr(startIndex, endIndex);
      	
     	$.ajax({
			type:"post",
			url:"${basePath}/medrecord/batchPaginationMedrecordImage",
			data:{'medicalResourceJsonStr':medicalResourceJsonStr, 'mrPageTypeId':mrpagetypeid, 'firstGuid':firstguid},
			success:function(data){
				if(data.success){
					/* var mrpagetypeObj = data.data[mrpagetypeid];
					if(mrpagetypeObj != null){
						$("#mrpagetype"+mrpagetypeid).html(mrpagetypeObj.pagination_count);
					}else{
						$("#mrpagetype"+mrpagetypeid).html("0");
					}
					
					//已经编页过的
					if(oldmrpagetypeid != null){
						var oldmrpagetypeObj = data.data[oldmrpagetypeid];
						if(oldmrpagetypeObj != null){
							$("#mrpagetype"+oldmrpagetypeid).html(oldmrpagetypeObj.pagination_count);
						}else{
							$("#mrpagetype"+oldmrpagetypeid).html("0");
						}
					}
					
					currentImage.setAttribute("mr-page_type_id", ""+mrpagetypeid);
					currentImage.setAttribute("data-filename", ""+mrpagetypeid);
					currentImage.setAttribute("data-index", ""+mrpagetypeid);
					checkedImage.removeAttr("checked");
					checkedImage.css("border-color", "green");
					var unPaginationFile=$("#filepage li[data-filename='0']");
			    	$("#unPaginationSpan").html(unPaginationFile.length);
			    	$("#filepage ul li").sort(sort_li).appendTo('#filepage ul');
					
			    	var pagination = $("#pagination").val();
			    	if(pagination==1){
			    		$("#"+data.msg).hide();
			    		paginationCount();
			    	} */
			    	
			    	 window.location.reload();
				}else{
					alert("病案编页失败！");
				}
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				 alert(XMLHttpRequest.status);
				 alert(XMLHttpRequest.readyState);
				 alert(textStatus);
			}
		});
		
	}
	
	function submitBatchPaginantion(mrPageType) {
		var startIndex = $("#batchChooseTemplate_startIndex").val();
		var endIndex = $("#batchChooseTemplate_endIndex").val();
		console.log("mrPageType="+mrPageType);
		batchPaginaionAjax(startIndex, endIndex, mrPageType);
		
	}
	
	//核对护理记录单
	function chooseLabelModal(startIndex, endIndex) {
		var startIndex1 = Math.min(startIndex, endIndex);
		var endIndex1 = Math.max(startIndex, endIndex);
		console.log(startIndex+"--"+endIndex);
		$("#batchChooseTemplate_startIndex").val("");
		$("#batchChooseTemplate_endIndex").val("");
		$("#batchChooseTemplate_startIndex").val(startIndex);
		$("#batchChooseTemplate_endIndex").val(endIndex);
		$('#batchChooseTemplate').modal('show');
	}
	

$(function(){
	$(".changeImgIndex").keypress(function(event) {
		event.stopPropagation();
	});
	
	$("#filepage li").keypress(function(event) {
		event.stopPropagation();
    	var checkedStr = $(this).attr("checked");
		if (checkedStr == "checked") {
			if (event.keyCode === 97) {
				//清除原来被选中的
				console.log("----按下了 A键----");
				if($(this).attr("s_batchChoose")=='s_batchChoose') {
					$(this).removeAttr("s_batchChoose");
					$(this).find('img').removeClass('TM');
				} else {
					$(this).attr("s_batchChoose", "s_batchChoose");
					$(this).siblings().removeAttr("s_batchChoose");
					$(this).find('img').addClass('TM');
					$(this).siblings().find('img').removeClass('TM');
				}
				//layer.msg('按A键成功!', {time:500});
			} else if (event.keyCode === 98) {
				console.log("-------按下了  B键--------");
				//判断之前是否选中了开始页,并且按下了 B键
				if (existsSBatchChoose()) {
					$(this).attr("e_batchChoose", "e_batchChoose");
					$(this).siblings().removeAttr("e_batchChoose");
					var sBatchChooseindex = getBatchChooseIndex("s_batchChoose");
					
					 if(sBatchChooseindex != -1) {
						 var eBatchChooseindex = getBatchChooseIndex("e_batchChoose");
						 //弹框选择编页的标签
						 chooseLabelModal(sBatchChooseindex, eBatchChooseindex);
						 
					 }	else {
						 console.log('----选中了开始页,并且按下了 B键获取开始页的下标没有获取到!------');
					 }
				}  else {
					layer.msg("在按B之前,请先按A键!",{time:500});
				}
			} else {
				//hot key
				var keyName = getKeyNameByKeyCode(event.keyCode);
				console.log('keyName='+keyName);
				
				if (null != keyName && "" != keyName) {
					var pageTypeId = getMrPageTypeIdByKeyName(keyName);
					var sortCode = getMrPageTypeSortCodeByKeyName(keyName);
					
					if (null != pageTypeId) {
						console.log('-----hot key success-----pageTypeId='+pageTypeId);
				
			          	var firstguid = $("#firstGuidHidden").val();
			         	var filehash = $(this).attr("file-hash");
			         	var oldmrpagetypeid = $(this).attr("mr-page_type_id");
			         	
			         	var currentLiObject = $(this);
			         	
			         	
			         	console.log("firstguid=" + firstguid);
			         	console.log("filehash=" + filehash);
			         	console.log("pageTypeId=" + pageTypeId);
			         	console.log("oldMrPageTypeId=" + oldmrpagetypeid);
			         	//String firstGuid,String fileHash,Integer mrPageTypeId,Integer oldMrPageTypeId
			         	$.ajax({
							type:"post",
							url:"${basePath}/medrecord/paginationMedrecordImage",
							data:{"firstGuid":firstguid,"fileHash":filehash, "mrPageTypeId":pageTypeId,"oldMrPageTypeId":oldmrpagetypeid},
							success:function(data){
								if(data!=null && data.success == true){
									//修改某个编页标签的总数
									var mrpagetypeObj = data.data[pageTypeId];
									
									if(mrpagetypeObj != null){	
										$("#mrpagetype"+pageTypeId).text(mrpagetypeObj.pagination_count);
									} else {
										$("#mrpagetype"+pageTypeId).text("0");
									}
									
									//已经某个编页标签过的总数
									if(oldmrpagetypeid != null){
										var oldmrpagetypeObj = data.data[oldmrpagetypeid];
										
										if(oldmrpagetypeObj != null){
											$("#mrpagetype"+oldmrpagetypeid).text(oldmrpagetypeObj.pagination_count);
										} else {
											$("#mrpagetype"+oldmrpagetypeid).text("0");
										}
									}
									
									var paginationStatus = $("#pagination").val();
									
									//未编页
									if (paginationStatus == 1) {
										//1当前页的下一页被选中
										filepage.removeAttr("checked");
										currentLiObject.next().trigger('click');
										currentLiObject.next().focus();
										//currentLiObject.next().attr("checked","checked");
										//currentLiObject.next().css("border-color", "red").siblings().css("border-color","#ccc");
										//2删除当前页
										currentLiObject.remove();
										//3重新计算总页数和未编页数
										$('#unPaginationSpan').text($('#filepage li').length);
										
									} else if (paginationStatus == 2) {
										//已编页
										currentLiObject.attr("mr-page_type_id", pageTypeId);
										currentLiObject.attr("data-filename", pageTypeId);
										//data-index --> sortCode
										currentLiObject.attr("data-index", sortCode);
										currentLiObject.removeAttr("checked");
										$(filepage).css("border-color","#ccc");
										//右边的编页标签变色
										 //编页标签设置为默认颜色
							           	$(".menulist li").css("background","#F7F8F8");
							           	//已经编页过的图片,编页标签设置为黄色
							           	$(".menulist li[page-type-id='"+pageTypeId+"']").css("background", "#FEC99C");
							       
							           	//重新排序
							           	$("#filepage ul li").sort(sort_li).appendTo('#filepage ul');
					                   var $objTop = currentLiObject[0].offsetTop; 
					                  
					                  //currentLiObject.focus();
					                   var h= $objTop;
					                    $(".filePage").animate({
					                     	scrollTop: h
					                     }, 500); 
									}
								}else{
									alert("病案编页失败！");
								}
								
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								 alert(XMLHttpRequest.status);
								 alert(XMLHttpRequest.readyState);
								 alert(textStatus);
							}
						}); 
						
					}
				}
				
				
			}
		}
		//-------end----
	});
	
	//获取图片列表
    var filepage = $("#filepage li");
    filepage.sort(sort_li).appendTo('#filepage ul');
    
    //获取编目菜单列表
    var menulist=$(".menulist li");
    
    $.each(menulist, function(index){
    	var mrPageTypeId = $(this).attr('page-type-id');
    	$(this).find('span').eq(0).text(getKeyNameByMrPageTypeId(mrPageTypeId)+$(this).find('span').eq(0).text());
    	
    	
    })
    
    //获取未编页图片列表
    var unPaginationFile=$("#filepage li[data-filename='0']");
    $("#unPaginationSpan").html(unPaginationFile.length);
    
    //定义未点击的图片
	//var filename,menuname;
    //点击图片列表
    $.each(filepage, function(i,item){
        $(item).on("click",function(){
        	//当前活动图片加红色边框,其他兄弟边框还是默认灰色
            $(this).css("border-color", "red").siblings().css("border-color","#ccc");
        	//已编页的边框设置为绿色
            $(this).siblings("[mr-page_type_id]").css("border-color","green");
            var checkedImages = $("#filepage li[checked='checked']");
            //去除所有li的checked状态
            filepage.removeAttr("checked");
            //当前的li为选中的状态
           	$(this).attr("checked","checked");
            
            //编页标签设置为默认颜色
           	$(".menulist li").css("background","#F7F8F8");
           	var mr_page_type_id =$(this).attr("mr-page_type_id");
           	//已经编页过的图片,编页标签设置为黄色
           	$(".menulist li[page-type-id='"+mr_page_type_id+"']").css("background","#FEC99C");
        })
    });
    
    //点击菜单绑定列表
    $.each(menulist, function(i,item){
        $(item).on("click",function() {
          //当前活动菜单加橘黄色背景，其他的还是默认灰色背景
          $(this).css("background","#FEC99C").siblings().css("background","#F7F8F8");
          var checkedImage = $("#filepage li[checked='checked']");
          var $menu_li_obj = $(this);
          //对选中的图片编页
          if(checkedImage.length != 0){
          	var currentImage = checkedImage.get(0);
          	var firstguid = $("#firstGuidHidden").val();
         	var mrpagetypeid =  $(this).attr("page-type-id");
         	var filehash = currentImage.getAttribute("file-hash");
         	var oldmrpagetypeid = currentImage.getAttribute("mr-page_type_id");
         	
         	$.ajax({
				type:"post",
				url:"${basePath}/medrecord/paginationMedrecordImage",
				data:{firstGuid:firstguid,fileHash:filehash, mrPageTypeId:mrpagetypeid,oldMrPageTypeId:oldmrpagetypeid},
				success:function(data){
					if(data!=null && data.success == true){
						var mrpagetypeObj = data.data[mrpagetypeid];
						if(mrpagetypeObj != null){	
							$("#mrpagetype"+mrpagetypeid).text(mrpagetypeObj.pagination_count);
						} else {
							$("#mrpagetype"+mrpagetypeid).text("0");
						}
						
						//已经某个编页标签过的总数
						if(oldmrpagetypeid != null){
							var oldmrpagetypeObj = data.data[oldmrpagetypeid];
							
							if(oldmrpagetypeObj != null){
								$("#mrpagetype"+oldmrpagetypeid).text(oldmrpagetypeObj.pagination_count);
							} else {
								$("#mrpagetype"+oldmrpagetypeid).text("0");
							}
						}
						
						var paginationStatus = $("#pagination").val();
						var sortCode =  $menu_li_obj.attr('sortCode');
						
						//未编页
						if (paginationStatus == 1) {
							//1当前页的下一页被选中
							filepage.removeAttr("checked");
							checkedImage.next().trigger('click');
							checkedImage.next().focus();
							//currentLiObject.next().attr("checked","checked");
							//currentLiObject.next().css("border-color", "red").siblings().css("border-color","#ccc");
							//2删除当前页
							checkedImage.remove();
							//3重新计算总页数和未编页数
							$('#unPaginationSpan').text($('#filepage li').length);
							
						} else if (paginationStatus == 2) {
							//已编页
							checkedImage.attr("mr-page_type_id", mrpagetypeid);
							checkedImage.attr("data-filename", mrpagetypeid);
							//data-index --> sortCode
							checkedImage.attr("data-index", sortCode);
							checkedImage.removeAttr("checked");
							$(filepage).css("border-color","#ccc");
							//右边的编页标签变色
							 //编页标签设置为默认颜色
				           	$(".menulist li").css("background","#F7F8F8");
				           	//已经编页过的图片,编页标签设置为黄色
				           	$(".menulist li[page-type-id='"+mrpagetypeid+"']").css("background", "#FEC99C");
				       
				           	//重新排序
				           	$("#filepage ul li").sort(sort_li).appendTo('#filepage ul');
		                   var $objTop = checkedImage[0].offsetTop; 
		                  
		                  //currentLiObject.focus();
		                   var h= $objTop;
		                    $(".filePage").animate({
		                     	scrollTop: h
		                     }, 500); 
						}
						
						/* var mrpagetypeObj = data.data[mrpagetypeid];
						if(mrpagetypeObj != null){
							$("#mrpagetype"+mrpagetypeid).html(mrpagetypeObj.pagination_count);
						}else{
							$("#mrpagetype"+mrpagetypeid).html("0");
						}
						
						//已经编页过的
						if(oldmrpagetypeid != null){
							var oldmrpagetypeObj = data.data[oldmrpagetypeid];
							if(oldmrpagetypeObj != null){
								$("#mrpagetype"+oldmrpagetypeid).html(oldmrpagetypeObj.pagination_count);
							}else{
								$("#mrpagetype"+oldmrpagetypeid).html("0");
							}
						}
						
						currentImage.setAttribute("mr-page_type_id", ""+mrpagetypeid);
						currentImage.setAttribute("data-filename", ""+mrpagetypeid);
						currentImage.setAttribute("data-index", ""+mrpagetypeid);
						checkedImage.removeAttr("checked");
						checkedImage.css("border-color", "green");
						var unPaginationFile=$("#filepage li[data-filename='0']");
				    	$("#unPaginationSpan").html(unPaginationFile.length);
				    	$("#filepage ul li").sort(sort_li).appendTo('#filepage ul');
						
				    	var pagination = $("#pagination").val();
				    	if(pagination==1){
				    		$("#"+data.msg).hide();
				    		paginationCount();
				    	} */
				    	
				    	// window.location.reload();
					}else{
						alert("病案编页失败！");
					}
					
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					 alert(XMLHttpRequest.status);
					 alert(XMLHttpRequest.readyState);
					 alert(textStatus);
				}
			}); 
          }
          else{
          	 var menuname=$(this).attr("data-filename");
          	 var current_index = 0;
			          	 
			 $.each(filepage,function(i,item){
                /*判断li中data-filename是否跟menuname一样*/
                if($(item).attr("data-filename")==menuname){
                	if(current_index == 0){
                		/* 获取该标签距离顶部的高度  */
	                    var $objTop=$(item)[0].offsetTop;
	                    /* 获取文件图片第一个li的 offsetTop */
	                    var $firstTop=$(filepage).get(0).offsetTop;
	                    /*当前li要滚动的总高度*/
	                    var h=$objTop;
	                    
	                    $(".filePage").animate({
	                     scrollTop: h
	                     },500);
	                     current_index = 1;
                	}
                }
            })	//each end
          }
        });
    });
	});
            
            
    function addPageStatus(){
    	var firstGuid = $("#firstGuidHidden").val();
    	$.ajax({
    		type:"post",
    		url:"${basePath}/medrecord/addPaginationTreatementTrace",
    		data:{firstGuid:firstGuid},
    		success:function(data){
    			var name = $("#name").val();
     			var idCard = $("#idCard").val();
     			var outHospitalStartDate = $("#outHospitalStartDate").val();
     			var outHospitalEndDate = $("#outHospitalEndDate").val();
     			var mrId =$("#mrId").val();
     			var visitNumber = $("#visitNumber").val();
     			var currentPage = $("#currentPage").val();
     			window.location.href="${basePath}/medrecord/queryPaginationMedrecordImage?name="+name+"&idCard="+idCard+"&outHospitalStartDate="+outHospitalStartDate+"&outHospitalEndDate="+outHospitalEndDate+"&mrId="+mrId+"&visitNumber="+visitNumber+"&currentPage="+currentPage+"&paginationStatus=1";
    		}
    	})
    }
    
    //图片旋转
    function rotateImg(obj){
    	layer.confirm("您确认要对当前图片进行翻转操作吗?请确认!", {
            btn : [ '确认翻转', '取消翻转' ]//按钮
        }, function(index) {
        	
        	var $this = $(obj);
        	var $li = $this.closest("li");
        	var $img = $li.find("img");
        	var imagePath =$this.attr("imgpath");
        	var angle = 180;
        	
        	var hospitalizationNoteResourceUrl = $("#hospitalizationNoteResourceUrl").val();
        	layer.close(index);
        	
        	$.ajax({
        		type:"post",
        		data:{imagePath:imagePath,angle:angle},
        		url:"${basePath}/image/imageRotate",
        		success:function(data){
        			console.log("翻转180度结果 " + JSON.stringify(data));
        			var rootUrl = data.data;
        			
        			if(data.success){
        				$img.attr("src", rootUrl + imagePath+"?Date=" + new Date().getTime());
        				/* $img.rotate(
        						{
        							animateTo:angle,
	        						easing: $.easing.easeInOutExpo 
	        					}
        						);		 */
        				//window.location.reload();
        			}
        			
        		}
        	})
        }); 	
      
        	
    }
    
    function stopBubble(e){
    	  //一般用在鼠标或键盘事件上
    	  if(e && e.stopPropagation){
    	  //W3C取消冒泡事件
    	  e.stopPropagation();
    	  }else{
    	  //IE取消冒泡事件
    	  window.event.cancelBubble = true;
    	  }
    	  };
    
    function sortImage(obj){
    	
    	layer.confirm("您确认要修改图片顺序吗?请确认!", {
            btn : [ '确认', '取消' ]//按钮
        }, function(index) {
        	var $this = $(obj);
        	var $li = $this.closest("li");
        	var fileHash = $li.attr("id");
        	var $input = $this.prev();
        	var sortIndex = $input.val();
        	layer.close(index);
        	if(sortIndex==null || sortIndex=="" || sortIndex==undefined){
        		 layer.alert('序列不能为空!',{icon:1});
        		return;
        	}
        	
        	$.ajax({
        		type:"post",
        		data:{fileHash:fileHash,sortIndex:sortIndex},
        		url:"${basePath}/medrecord/imgSort",
        		success:function(data){
        			paginationShow();
        		}
        	});
        }); 

    }
    
    
    function deleteImg(obj){
    	layer.confirm("您确认要删除当前图片吗?请确认!", {
            btn : [ '确认删除', '取消删除' ]//按钮
        }, function(index) {
        	var $this = $(obj);
        	var $li = $this.closest("li");
      
        	var fileHash = $li.attr("id");
        	var firstGuid = $("#firstGuidHidden").val();
        	//alert(fileHash+"--"+firstGuid);
        	$.ajax({
				type:"post",
				url:"${basePath}/medrecord/removeMedrecordImage",
				data:{firstGuid:firstGuid,fileHash:fileHash},
				success:function(data){
					if(data!=null && data.success == true){
						$li.remove();
						//$("#totalPage").html(data.data);
						paginationShow();
						
					}else{
						 layer.alert('删除失败!',{icon:7});
					}
				}
			}); 
        	
        }); 
    }
    
    //删除某个编页标签所对应的所有图片
    function deleteCertainPageTypeImgs() {
    	$('#deleteCertainPageTypeImgsModal_form').get(0).reset();
    	$('#deleteCertainPageTypeImgsModal').modal('show');
    }
    
    function deleteCertainPageTypeImgs_button() {
		var pageTypeId = $('#select_deleteCertainPageTypeImg').val();
		var firstGuid = $("#firstGuidHidden").val();
		var dataform = {'firstGuid':firstGuid, 'pageTypeId':pageTypeId};
		var url = "${basePath}/medrecord/deleteCertainPageTypeImgs";
		
		$.ajax({
            type:"post",
            url:url,
            dataType:"json",
            data:dataform,
            success:function(result){
                 if(result.success){
                        window.location.reload();
                 }else{
                        alert(result.msg)
                 }
            },
            error:function(XMLHttpRequest, textStatus, errorThrown) {
                  if(XMLHttpRequest.status == 403) {
                         alert("没有权限!");
                  }
            }  //error end 
           
     }); //ajax 结束

    }
    
    
    
    
</script>













